import request from '@/config/axios'
import { getApiPath } from '@/config/api'

export function login(data) {
  return request({
    url: getApiPath('LOGIN'),
    method: 'post',
    data: {
      username: data.username,
      password: data.password
    }
  })
}

export function register(data) {
  return request({
    url: getApiPath('REGISTER'),
    method: 'post',
    data: {
      username: data.username,
      password: data.password,
      email: data.email,
      gender: '未设置',
      userId: 0
    }
  })
}

export const getUserInfo = async () => {
  try {
    const userId = localStorage.getItem('userId')
    if (!userId) {
      throw new Error('用户ID不存在')
    }
    
    const response = await request({
      url: getApiPath('USER_PROFILE'),
      method: 'get',
      params: {
        userId: parseInt(userId)
      }
    })
    return response
  } catch (error) {
    console.error('获取用户信息失败:', error)
    throw error
  }
}

export const getUserAvatar = async () => {
  try {
    const userId = localStorage.getItem('userId')
    if (!userId) {
      throw new Error('用户ID不存在')
    }
    
    const response = await request({
      url: '/api/user/avatar',
      method: 'get',
      params: {
        userId: parseInt(userId)
      }
    })
    return response
  } catch (error) {
    console.error('获取用户头像失败:', error)
    throw error
  }
}

export function updateUserInfo(data) {
  // 转换数据格式以匹配后端要求
  const requestData = {
    profileId: data.profileId,
    userId: data.id || localStorage.getItem('userId'),
    name: data.nickname,
    gender: data.gender === 'male' ? '男' : '女',
    age: data.age,
    height: data.height,
    weight: data.weight,
    activityLevel: convertActivityLevelToBackend(data.activityLevel)
  }
  
  return request({
    url: getApiPath('UPDATE_PROFILE'),
    method: 'put',
    data: requestData
  })
}

// 添加活动水平转换函数
function convertActivityLevelToBackend(level) {
  const levelMap = {
    'sedentary': '低',
    'lightly_active': '中',
    'moderately_active': '中',
    'very_active': '高'
  }
  return levelMap[level] || '中'
}

export function logout() {
  return request({
    url: getApiPath('LOGOUT'),
    method: 'post'
  })
}

export function exportUserData() {
  return request({
    url: getApiPath('EXPORT_DATA'),
    method: 'get'
  })
}

export function deleteUserAccount() {
  return request({
    url: getApiPath('DELETE_ACCOUNT'),
    method: 'delete'
  })
}

export function updatePassword(data) {
  return request({
    url: '/user/password',
    method: 'put',
    data
  })
}

export function resetPassword(data) {
  return request({
    url: '/user/reset-password',
    method: 'post',
    data
  })
}

